<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 卡片视图 -->
      <el-card class="box-card">
        <!-- --------------------------------------------------------搜索框部分----------------------------------------------------------------- -->
        <el-row :gutter="20">
          <el-col :span="18">
            <el-row :gutter="20">
              <el-col :span="8"> <el-input v-model="queryInfo.username" placeholder="请用户名搜索"></el-input></el-col>
              <el-col :span="6">
                <el-button class="btnsuser" size="small" plain @click="emptyuser">清空</el-button>
                <el-button class="btnsuser" size="small" type="primary" plain @click="searchuser">搜索</el-button>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="6">
            <el-button class="rightbtn" type="success" icon="el-icon-edit" @click="addDialogVisible = true">新增用户</el-button>
          </el-col>
        </el-row>

        <!-- --------------------------------------------------------提示信息部分----------------------------------------------------------------- -->
        <el-alert :title="countstext" type="info" show-icon :closable="false"> </el-alert>

        <!-- -----------------------------------------------------------表格部分------------------------------------------------ -->
        <el-table v-loading="loading" element-loading-text="给我一点时间" :data="usersList" style="width: 100%">
          <el-table-column align="center" prop="id" label="序号"> </el-table-column>
          <el-table-column align="center" prop="email" label="邮箱"> </el-table-column>
          <el-table-column align="center" prop="phone" label="联系电话"> </el-table-column>
          <el-table-column align="center" prop="username" label="用户名"> </el-table-column>
          <el-table-column align="center" prop="permission_group_title" label="权限组名称"> </el-table-column>
          <el-table-column align="center" prop="role" label="角色"> </el-table-column>
          <!-- 操作按钮部分 -->
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <!-- 编辑按钮 -->
              <el-button plain type="primary" icon="el-icon-edit" circle @click="edituser(scope.row)"></el-button>
              <!-- 删除按钮 -->
              <el-button v-if="scope.row.id !== 2" plain type="danger" icon="el-icon-delete" circle @click="removeById(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- ---------------------------------------------------------------分页功能---------------------------------------------- -->
        <el-pagination
          style="text-align:right;margin-top:20px"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="Number(page)"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="Number(pagesize)"
          layout="total,prev, pager, next, sizes,  jumper"
          :total="counts"
        >
        </el-pagination>
      </el-card>
      <!-- ------------------------------------------------------------------添加用户弹出层-------------------------------------- -->
      <el-dialog title="创建用户" :visible.sync="addDialogVisible" width="50%" @close="closeAddForm">
        <el-form ref="addFormRef" :model="addForm" :rules="addFromRules" label-width="120px" style="width: 400px; margin-left:120px;">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-input v-model="addForm.role"></el-input>
          </el-form-item>
          <el-form-item label="权限组名称">
            <el-select v-model="addForm.permission_group_id" placeholder="请选择">
              <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="addForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="介绍">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="addForm.introduction"> </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- ---------------------------------------------------------------编辑弹出层---------------------------------------------- -->
      <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="50%">
        <el-form ref="addFormRef" :model="editForm" :rules="editFromRules" label-width="120px" style="width: 400px; margin-left:120px;">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>

          <el-form-item label="角色">
            <el-input v-model="editForm.role"></el-input>
          </el-form-item>
          <el-form-item label="权限组名称">
            <el-select v-model="editForm.permission_group_id" placeholder="请选择">
              <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="editForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="介绍">
            <el-input type="textarea" :rows="2" placeholder="please input " v-model="editForm.introduction"> </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="edituserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 导入相关的axios
import { list, add, detail, update, remove } from '@/api/base/users.js'
import { permissionlist } from '@/api/base/permissions.js'
export default {
  name: 'base-users',
  data () {
    return {
      loading: true,
      // 用户列表数据来源
      usersList: [],
      counts: 0, // 总条数,用在alert和分页上
      pagesize: '', //页大小
      pages: 1, // 总页数
      page: '', // 当前页码
      countstext: '',
      // 用户相关的请求参数
      queryInfo: {
        page: 1,
        pagesize: 10,
        keyword: null,
        disabled: 0
      },
      addDialogVisible: false, // 添加用户弹出层的显示与隐藏
      // 添加用户的数据来源
      addForm: {
        username: '',
        email: '',
        password: '',
        role: '',
        permission_group_id: '',
        phone: '',
        introduction: ''
      },

      //添加用户验证规则部分
      addFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 5 到 10个字符', trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },

      // 权限组的数据来源
      options: [],
      // -------------------------------------------------------编辑框部分----------------------------------------------------------
      // 编辑弹框的显示与隐藏
      editDialogVisible: false,
      // 编辑框的数据来源
      editForm: {},
      // 编辑框的验证规则部分
      editFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 5 到 10个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    // 获取用户相关信息
    this.getUserList()
    // 获取权限组的信息
    this.getPermission()
  },
  methods: {
    async getUserList () {
      try {
        const { data: res } = await list(this.queryInfo)
        this.usersList = res.list
        this.counts = res.counts
        this.countstext = `共${this.counts}条数据`
        // console.log(res)
      } catch (error) {
        // console.log(error)
        this.$message.error('获取用户信息失败!')
      }
      this.loading = false
    },
    // 清空
    emptyuser () {
      this.queryInfo.username = ''
      this.getUserList()
    },
    // 搜索功能
    searchuser () {
      this.getUserList()
    },
    // 当前每页显示多少数据
    handleSizeChange (pagesize) {
      this.queryInfo.pagesize = pagesize
      this.getUserList()
    },
    // 当前多少页
    handleCurrentChange (page) {
      this.queryInfo.page = page
      // console.log(this.page)
      this.getUserList()
    },

    // 重置表单的验证效果,弹框关闭清除表单的验证结果
    closeAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    // 新增用户,进行调单验证
    addUserInfo () {
      this.$refs.addFormRef.validate(async valid => {
        // 验证不通过
        if (!valid) return
        // 验证通过
        try {
          const { data } = await add({
            username: this.addForm.username,
            email: this.addForm.email,
            password: this.addForm.password,
            role: this.addForm.role,
            permission_group_id: this.addForm.permission_group_id,
            phone: this.addForm.phone,
            introduction: this.addForm.introduction
            // avatar: this.addForm.avatar
          })
          // console.log(data)
          // 更新视图
          this.$message.success('新增用户成功!')
          this.getUserList()
        } catch (error) {
          // 错误提醒
          this.$message.error('新增用户失败')
          // console.log(error)
        }
      })

      // 关闭弹框
      this.addDialogVisible = false
    },
    //  获取权限组的信息
    async getPermission () {
      const { data: res } = await permissionlist(this.queryInfo)
      // console.log(res)
      this.options = res.list
      // console.log(this.options)
    },

    // 编辑用户的相关方法
    async edituser (row) {
      // 显示编辑框
      this.editDialogVisible = true
      // 根据id获取相关数据
      // console.log(id)
      const { data } = await detail(row)
      this.editForm = data
      // console.log(data)
    },

    // 点击确认,确认修改
    async edituserInfo () {
      try {
        const { data } = await update(this.editForm)
        // 更新视图
        this.getUserList()
        this.$message.success('更新用户信息成功!')
        // console.log(data)
      } catch (error) {
        console.log(error)
        this.$message.error('更新用户信息失败!')
      }
      // 关闭弹窗
      this.editDialogVisible = false
    },
    // 删除用户操作
    async removeById (row) {
      // console.log(row.id)
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('您取消了操作')
      }
      try {
        const { data } = await remove(row)
        // 更新视图
        this.getUserList()
        // 成功提醒
        this.$message.success('删除成功!')
        // console.log(data)
      } catch (error) {
        // console.log(error)
        this.$message.error('删除失败!')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-alert {
  margin: 20px 0;
}
.dialog-footer {
  display: block;
  text-align: center;
}
// .el-from {
//   width: 400px !important;
//   margin-left: 120px;
// }
.el-input__inner {
  margin-bottom: 22px;
}
.btnsuser {
  height: 36px;
}
// .rightbtn {
//   float: rigth !important;
//   height: 35px;
// }
button.el-button--success {
  float: right !important;
}
</style>
